import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:sinosheets/components/NetWorkImage/NetworkImageWidget.dart';
import 'package:sinosheets/route/route_utils.dart';

import 'logic.dart';

class RecommendedShopPage extends StatefulWidget {
  const RecommendedShopPage({Key? key}) : super(key: key);

  @override
  State<RecommendedShopPage> createState() => _RecommendedShopPageState();
}

class _RecommendedShopPageState extends State<RecommendedShopPage> {
  final RecommendedShopLogic logic = Get.put(RecommendedShopLogic());

  @override
  Widget build(BuildContext context) {
    return GetBuilder<RecommendedShopLogic>(builder: (get) {
      return Scaffold(
        appBar: AppBar(
          title: Text('Recommended Shop', style: TextStyle(fontSize: 20.r, fontWeight: FontWeight.bold)),
          centerTitle: true,
        ),
        body: GridView.builder(
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2,
            childAspectRatio: 0.80,
          ),
          itemBuilder: (context, index) {
            return _buildRecommendedShopItem(get.shopList[index]);
          },
          itemCount: get.shopList.length,
        ),
      );
    });
  }

  Widget _buildRecommendedShopItem(Map<String, dynamic> item) {
    return GestureDetector(
      onTap: () => _onShopTap(item),
      child: Container(
        margin: EdgeInsets.all(8.r),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12.r),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.05),
              blurRadius: 8.r,
              offset: Offset(0, 2.r),
            ),
          ],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 店铺Logo区域
            Expanded(
              flex: 3,
              child: Container(
                width: double.infinity,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.vertical(top: Radius.circular(12.r)),
                  color: const Color(0xFFF5F5F5),
                ),
                child: ClipRRect(
                  borderRadius: BorderRadius.vertical(top: Radius.circular(12.r)),
                  child: NetworkImageWidget(
                    url: item['shopLogo'],
                    fit: BoxFit.cover,
                  ),
                ),
              ),
            ),

            // 店铺信息区域
            Expanded(
              flex: 2,
              child: Padding(
                padding: EdgeInsets.all(10.r),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 店铺名称
                    Text(
                      item['shopName'] ?? '',
                      style: TextStyle(
                        fontSize: 14.r,
                        fontWeight: FontWeight.w600,
                        color: Colors.black87,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),

                    SizedBox(height: 4.r),

                    // 店铺来源类型
                    Container(
                      padding: EdgeInsets.symmetric(horizontal: 6.r, vertical: 2.r),
                      decoration: BoxDecoration(
                        color: _getSourceTypeColor(item['sourceType']),
                        borderRadius: BorderRadius.circular(4.r),
                      ),
                      child: Text(
                        _getSourceTypeText(item['sourceType']),
                        style: TextStyle(
                          fontSize: 10.r,
                          color: Colors.white,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ),

                    SizedBox(height: 4.r),

                    // 店铺ID
                    Text(
                      'ID: ${item['shopId'] ?? ''}',
                      style: TextStyle(
                        fontSize: 10.r,
                        color: Colors.grey,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 获取来源类型颜色
  Color _getSourceTypeColor(String? sourceType) {
    switch (sourceType) {
      case 'wd':
        return const Color(0xFF4CAF50); // 微店 - 绿色
      case 'tb':
        return const Color(0xFFFF6B35); // 淘宝 - 橙色
      case 'jd':
        return const Color(0xFFE91E63); // 京东 - 粉色
      case 'pdd':
        return const Color(0xFFFFEB3B); // 拼多多 - 黄色
      default:
        return const Color(0xFF9E9E9E); // 默认 - 灰色
    }
  }

  /// 获取来源类型文本
  String _getSourceTypeText(String? sourceType) {
    switch (sourceType) {
      case 'wd':
        return 'Weidian';
      case 'tb':
        return 'Taobao';
      case 'jd':
        return 'JD';
      case 'pdd':
        return 'Pinduoduo';
      default:
        return 'Other';
    }
  }

  /// 店铺点击事件
  void _onShopTap(Map<String, dynamic> item) {
    String shopUrl = item['shopUrl'] ?? '';
    if (shopUrl.isNotEmpty) {
      _openShopUrl(item);
    } else {
      // 显示店铺信息
      Get.dialog(
        AlertDialog(
          title: const Text('Shop Information'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('Shop Name: ${item['shopName'] ?? ''}'),
              SizedBox(height: 8.r),
              Text('Shop ID: ${item['shopId'] ?? ''}'),
              SizedBox(height: 8.r),
              Text('Source: ${_getSourceTypeText(item['sourceType'])}'),
              SizedBox(height: 8.r),
              Text('Sort: ${item['sort'] ?? 0}'),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Get.back(),
              child: const Text('Close'),
            ),
          ],
        ),
      );
    }
  }

  /// 打开店铺链接
  void _openShopUrl(Map<String, dynamic> item) {
    String shopUrl = item['shopUrl'] ?? '';

    ///跳转itaobuy店铺
    ///拼接规则：https://www.itaobuy.com/shop-detail?url=https%3A%2F%2Fweidian.com%2F%3Fuserid%3D1736445632
    if (shopUrl.isNotEmpty) {
      String url = 'https://www.itaobuy.com/shop-detail?url=${Uri.encodeComponent(shopUrl)}';
      RouteUtils.toWebView(url: url);
    }
  }

  @override
  void dispose() {
    Get.delete<RecommendedShopLogic>();
    super.dispose();
  }
}
